#import "SMHomeViewController.h"
#import <Masonry/Masonry.h>
#import "SMHomeListController.h"
#import "../../Views/Components/SMCategoryBarView.h"

@interface SMHomeViewController () <UIPageViewControllerDataSource, UIPageViewControllerDelegate, UIScrollViewDelegate>
@property(nonatomic, strong) SMCategoryBarView *categoryBar;
@property(nonatomic, strong) UIPageViewController *pageVC;
@property(nonatomic, copy)   NSArray<NSString *> *categories;
@property(nonatomic, copy)   NSArray<SMHomeListController *> *pages;

// 联动用
@property (nonatomic, weak)   UIScrollView *pageScroll;
@property (nonatomic, assign) NSInteger movingFromIndex;
@property (nonatomic, assign) NSInteger movingToIndex;
@property (nonatomic, assign) BOOL isInteracting;
@end

@implementation SMHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"首页";
    self.view.backgroundColor = UIColor.systemBackgroundColor;

    self.categories = @[@"重废", @"统废", @"剪切料", @"破碎料", @"不锈钢"];

    // 顶部分类栏
    self.categoryBar = [SMCategoryBarView new];
    self.categoryBar.titles = self.categories;
    __weak typeof(self) weakSelf = self;
    self.categoryBar.onSelect = ^(NSInteger index) {
        [weakSelf switchToIndex:index animated:YES];
    };
    [self.view addSubview:self.categoryBar];
    [self.categoryBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(44);
    }];

    // 子页
    NSMutableArray *arr = [NSMutableArray array];
    for (NSString *c in self.categories) {
        [arr addObject:[[SMHomeListController alloc] initWithCategory:c]];
    }
    self.pages = arr;

    // PageVC
    self.pageVC = [[UIPageViewController alloc]
                   initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
                   navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                   options:nil];
    self.pageVC.dataSource = self;
    self.pageVC.delegate   = self;
    [self.pageVC setViewControllers:@[self.pages.firstObject]
                          direction:UIPageViewControllerNavigationDirectionForward
                           animated:NO
                         completion:nil];

    [self addChildViewController:self.pageVC];
    [self.view addSubview:self.pageVC.view];
    [self.pageVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.categoryBar.mas_bottom).offset(6);
        make.left.right.bottom.equalTo(self.view);
    }];
    [self.pageVC didMoveToParentViewController:self];

    // 获取内部的 scrollView
    for (UIView *v in self.pageVC.view.subviews) {
        if ([v isKindOfClass:UIScrollView.class]) {
            self.pageScroll = (UIScrollView *)v;
            self.pageScroll.delegate = self;
            break;
        }
    }
    self.movingFromIndex = NSNotFound;
    self.movingToIndex   = NSNotFound;
}

#pragma mark - 切换页面（点击栏目）
- (void)switchToIndex:(NSInteger)index animated:(BOOL)animated {
    UIViewController *cur = self.pageVC.viewControllers.firstObject;
    NSInteger curIdx = [self.pages indexOfObject:(SMHomeListController *)cur];
    if (curIdx == NSNotFound || curIdx == index) return;

    UIPageViewControllerNavigationDirection dir =
        (index > curIdx) ? UIPageViewControllerNavigationDirectionForward
                         : UIPageViewControllerNavigationDirectionReverse;

    // 提前设置指示条，防止“跳多一格”
    [self.categoryBar setSelectedIndex:index animated:YES];

    __weak typeof(self) weakSelf = self;
    [self.pageVC setViewControllers:@[self.pages[index]]
                          direction:dir
                           animated:animated
                         completion:^(BOOL finished) {
        weakSelf.isInteracting   = NO;
        weakSelf.movingFromIndex = NSNotFound;
        weakSelf.movingToIndex   = NSNotFound;
    }];
}

#pragma mark - UIPageViewControllerDataSource
- (UIViewController *)pageViewController:(UIPageViewController *)p viewControllerBeforeViewController:(UIViewController *)vc {
    NSInteger idx = [self.pages indexOfObject:(SMHomeListController *)vc];
    if (idx == NSNotFound || idx == 0) return nil;
    return self.pages[idx - 1];
}
- (UIViewController *)pageViewController:(UIPageViewController *)p viewControllerAfterViewController:(UIViewController *)vc {
    NSInteger idx = [self.pages indexOfObject:(SMHomeListController *)vc];
    if (idx == NSNotFound || idx >= self.pages.count - 1) return nil;
    return self.pages[idx + 1];
}

#pragma mark - 过渡开始（锁定 from/to）
- (void)pageViewController:(UIPageViewController *)pageViewController
  willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers {
    UIViewController *current = pageViewController.viewControllers.firstObject;
    NSInteger from = [self.pages indexOfObject:(SMHomeListController *)current];
    NSInteger to   = [self.pages indexOfObject:(SMHomeListController *)pendingViewControllers.firstObject];
    self.movingFromIndex = (from == NSNotFound ? 0 : from);
    self.movingToIndex   = (to   == NSNotFound ? self.movingFromIndex : to);
    self.isInteracting   = YES;
}

#pragma mark - 过渡结束/取消（归位 & 清理）
- (void)pageViewController:(UIPageViewController *)pageViewController
 didFinishAnimating:(BOOL)finished
 previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers
    transitionCompleted:(BOOL)completed {
    if (completed) {
        NSInteger idx = [self.pages indexOfObject:(SMHomeListController *)pageViewController.viewControllers.firstObject];
        if (idx != NSNotFound) [self.categoryBar setSelectedIndex:idx animated:YES];
    } else {
        if (self.movingFromIndex != NSNotFound) {
            [self.categoryBar setSelectedIndex:self.movingFromIndex animated:YES];
        }
    }
    self.isInteracting   = NO;
    self.movingFromIndex = NSNotFound;
    self.movingToIndex   = NSNotFound;
}

#pragma mark - UIScrollViewDelegate（联动指示条）
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (!self.isInteracting) return;
    if (self.movingFromIndex == NSNotFound || self.movingToIndex == NSNotFound) return;

    CGFloat width   = scrollView.bounds.size.width;
    if (width <= 0) return;

    CGFloat offsetX = scrollView.contentOffset.x;
    CGFloat progress = 0;

    if (self.movingToIndex > self.movingFromIndex) {
        // 右向左：width -> 2*width
        progress = (offsetX - width) / width;
    } else if (self.movingToIndex < self.movingFromIndex) {
        // 左向右：width -> 0
        progress = (width - offsetX) / width;
    }
    progress = MAX(0, MIN(1, progress));
    [self.categoryBar updateIndicatorFromIndex:self.movingFromIndex
                                       toIndex:self.movingToIndex
                                      progress:progress];
}
@end
